﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flower.Actors
{
    public class ObjectPool<T> 
        where T: class, new()
    {
        private const int DEFAULT_POOL_CAPACITY = 10;

        private readonly object _syncRoot = new object();
        private readonly Action<T> _cleanup;
        private readonly Action<T> _init;
        private T[] _data;
        private int _top;

        public ObjectPool()
            : this(DEFAULT_POOL_CAPACITY, null, null)
        {
        }

        public ObjectPool(Action<T> init, Action<T> cleanup)
            : this(DEFAULT_POOL_CAPACITY, init, cleanup)
        {
        }

        public ObjectPool(int capacity, Action<T> init, Action<T> cleanup)
        {
            _cleanup = cleanup;
            _init = init;
            _data = new T[capacity];
            _top = 0;
        }

        private T Init(T obj)
        {
            if (_init != null)
            {
                _init(obj);
            }

            return obj;
        }

        private T Cleanup(T obj)
        {
            if (_cleanup != null)
            {
                _cleanup(obj);
            }

            return obj;
        }

        public T Get()
        {
            if (_top > 0)
            {
                lock (_syncRoot)
                {
                    if (_top > 0)
                    {
                        return Init(_data[--_top]);
                    }
                    else
                    {
                        return Init(new T());
                    }
                }
            }
            else
            {
                return Init(new T());
            }
        }

        public void Return(T obj)
        {
            lock (_syncRoot)
            {
                if (_top == _data.Length)
                {
                    var newData = new T[_data.Length * 2];
                    Array.Copy(_data, newData, _data.Length);
                    _data = newData;
                }

                _data[_top++] = Cleanup(obj);
            }
        }
    }
}
